/**
 * 
 */
package trungsi.gea.photos.controller;

import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.integration.spring.SpringBean;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;

import trungsi.gea.photos.domain.Folder;
import trungsi.gea.photos.service.FolderService;
import trungsi.gea.photos.util.JsonUtils;

/**
 * @author trungsi
 *
 */
@UrlBinding("/folder-admin")
public class FolderActionBean extends SecurityActionBean {

	private static Log log = LogFactory.getLog(FolderActionBean.class);
	
	@SpringBean
	private FolderService folderService;
	
	private Folder folder;
	
	public void setFolder(Folder folder) {
		this.folder = folder;
	}
	
	public Folder getFolder() {
		return folder;
	}
	
	@HandlesEvent("save")
	public Resolution save() {
		//System.out.println(getContext().getRequest().getParameter("folder.name"));
		try {
			folderService.save(folder);
			JSONObject json = new JSONObject();
			json.put("success", true);
			json.put("folder", JsonUtils.toJson(folder));
			
			return new StreamingResolution("text/javascript", json.toString());
		} catch (Exception e) {
			log.error(e);
			return new StreamingResolution("text/javascript", "{success : false, error : '" + e + "'}");
		}
	}	
	
	public Resolution delete() {
		if (folder != null) {
			try {
				folderService.delete(folder);
				return new StreamingResolution("text/javascript", "{success : true}");
			} catch (Exception e) {
				log.error(e);
				return new StreamingResolution("text/javascript", "{success : false, error : '" + e.toString().replaceAll("\n", "\\n") + "'}");
			}
		} else {
			return new StreamingResolution("text/javascript", "{success : false, error : 'folder not found'}");
		}
	}
	
	@HandlesEvent("deleteAll")
	public Resolution deleteAll() {
		for (Folder folder : folderService.findAll()) {
			folderService.delete(folder);
		}
		return new StreamingResolution("text/html", "{success : true}");
	}
}
